layui.use(['layer', 'jquery', 'util', 'form','laytpl', 'echarts','configs'], function () {
    let layer = layui.layer,
        $ = layui.jquery,
        form = layui.form,
        laytpl = layui.laytpl,
        echarts = layui.echarts,
        config = layui.configs;
    let timer = null;
    let periods = $('.right-part select.periods :selected').val();
    let myChart = echarts.init(document.getElementById("quantity-pie"));
    let moCount = null; // 当期马达总个数
    var quantityTpl = $('#quantity-tpl').html(), motorsTpl = $('#motors-tpl').html();
    form.render();
    getMotors();
    timeFun(getMotors,config.motorInter)();
    function timeFun(func, time) {
        return function intervalFun() {
            if(JSON.parse(sessionStorage.getItem('curMenu')).url == '/dashboard'){
                timer = setTimeout(function () {
                    func();
                    intervalFun();
                }, time);
            }
        };
    }
    //左上-数量
    function getQuantity(list){
        let arr = [
            {value: list.totalNum ,label: '总数', name: 'totalNum', color: ''},
            {value:list.offlineNum ,label: '离线', name: 'offlineNum', color: 'ftGray'},
            {value:list.normalNum ,label: '正常', name: 'normalNum', color: 'ftGreen'},
            {value:list.exceptNum ,label: '异常', name: 'exceptNum', color: 'ftRed'},
            {value:list.maintainNum ,label: '保养', name: 'maintainNum', color: 'ftBlue'},
            {value:list.normalRate ,label: '正常率', name: 'normalRate', color: 'ftGreen'}
        ];
        laytpl(quantityTpl).render({list: arr}, function(html){
            $('#quantity').html(html)
        });
        getPie(arr);
    }
    function getPie(list){
        let data = [].concat.apply([], list); // 复制数组
        data.shift();
        data.pop();
        var datalist = [];
        for(var i=0;i<data.length;i++){
            datalist.push({
                name: data[i].label,
                value: data[i].value,
                itemStyle: {
                    normal: {
                        color: pieColor(data[i].color)
                    }
                }})
        }
        let option = {
            grid: {
                containLabel: true
            },
            series: [
                {
                    name: '状态占比',
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '60%'],
                    label: {
                        show: true,
                        fontSize: 14,
                        formatter: '{b}：\n{d}%'
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    data: datalist
                }
            ]
        };
        myChart.setOption(option);
    }
    window.onresize = function () {
        myChart.resize();
    };
    function pieColor(color){
        let co = '';
        switch(color) {
            case 'ftGray':
                co = '#9e9e9e';
                break;
            case 'ftGreen':
                co = '#28d428';
                break;
            case 'ftRed':
                co = '#fe2216';
                break;
            case 'ftBlue':
                co = '#00BCD4';
                break;
            default:
                co = '#9e9e9e';
        }
        return co
    }
    // 获取报警信息
    function getAlertList(list){
        let lis = '';
        if(list.length === 0){
            lis = '<li style="text-align: center;border: 0;">无异常</li>';
        }else{
            for (let i = 0; i < list.length; i++) {
                lis += '<li>【' + list[i].alertTime + '】'+ list[i].alertMsg + '</li>'
            }
        }
        $(".alertList ul").html(lis);
    }

    // 查当期马达信息
    function getMotors(){
        $.ajax({
            url: config.motorBaseUrl + "/monitor/dashboard/v1.0",
            type: "post",
            datatype: "json",
            data: {
                periods: periods
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    // 数量+饼图
                    let statisticInfo = result.data.statisticInfo;
                    moCount = statisticInfo.totalNum;
                    getQuantity(statisticInfo);
                    // 最新异常
                    let exceptionLatest = result.data.exceptionLatest;
                    getAlertList(exceptionLatest);
                    // 马达展示
                    let motorList = result.data.data;
                    laytpl(motorsTpl).render({list: motorList}, function(html){
                        $('#motors-wrap').html(html);
                    });
                    form.render('checkbox');
                    var isAll = true;
                    motorList.forEach(item =>{
                        item.motorInfos.forEach(ite => {
                            if(ite.moOpenState == '-1'){
                                isAll = false
                            }
                            return;
                        });
                        return;
                    });
                    form.val("maintain", {
                        "allMaintain": isAll
                    });
                } else {
                    layer.alert(result.stateMsg);
                }
            },
            // complete: function () {
            //     clearInterval(timer);
            //     // 如果是当前tab，启用定时器
            //     if(JSON.parse(sessionStorage.getItem('curMenu')).url == '/dashboard'){
            //         // timer = setTimeout(function(){
            //         //     getMotors();
            //         // }, config.motorInter);
            //     }else{
            //         // 非当前tab，清除定时器
            //         clearInterval(timer);
            //     }
            // }
        })
    }

    let layerIndex = null;
    $('body').on('click','.right-part .motor img',function(){
        let that = this;
        layer.closeAll();
        $.ajax({
            url: config.motorBaseUrl + "/monitor/recent/v1.0", // 暂时用历史查询接口
            type: "post",
            datatype: "json",
            data: {
                moId: $(that).attr('data-mo')
            },
            success: function (result) {
                if(result.stateCode == 0){
                    var data = result.data;
                    var html = laytpl($('#latest-tpl').html()).render({list: data});
                    layerIndex = layer.open({
                        type: 1,
                        offset: 'rb',
                        shade: 0,
                        area: ['500px', '300px'],
                        title: $(that).attr('data-area') + $(that).attr('alt') + ' 最新振动烈度',
                        content: html
                    });
                }else{
                    layer.msg(result.stateMsg);
                }
            }
        });
    });
    // $('body').on('mouseleave','.right-part .motor img',function(){
    //    layer.closeAll();
    // });

    $('button.close-alarm').click(function() {
        $.ajax({
            url: config.motorBaseUrl + "/monitor/closeAlarmLight/v1.0",
            type: "post",
            datatype: "json",
            data: {
                periods: periods
            },
            success: function (result) {
                layer.msg(result.stateMsg);
            }
        })
    });
    //监听期别选择
    form.on('select(periods)', function (data) {
        periods = data.value;
        // clearInterval(timer);
        // getMotors();
        clearTimeout(timer);
        timeFun(getMotors,config.motorInter)();
    });

    //监听 全部保养 开关
    form.on('switch(allMaintain)', function (data) {
        let moId = -1 , openState = data.elem.checked ? 1 : -1;
        makeProcess(moId, openState);
    });

    //监听 单个马达 保养 开关
    let moOpenState = 0;
    form.on('switch(motorMaintain)', function (data) {
        let moId = $(data.elem).attr('data-moid'),
            openState = null;
        if(data.elem.checked){
            openState = 1;
            moOpenState++; // 记录单个马达保养数量
        }else{
            openState = -1;
            moOpenState--;
        }
        form.val("maintain", {
            "allMaintain": moOpenState === moCount
        });
        makeProcess(moId, openState);
    });

    //保养/开线
    // moId： -1表示所有马达 ， openState：1.开线，-1.关线(保养)
    function makeProcess(moId, openState){
        $.ajax({
            url: config.motorBaseUrl + "/monitor/makeProcess/v1.0",
            type: "post",
            datatype: "json",
            data: {
                periods: periods,
                moId: moId,
                openState: openState
            },
            success: function (result) {
                if(result.stateCode === 0){
                    // clearInterval(timer);
                    // getMotors();
                    clearTimeout(timer);
                    timeFun(getMotors,config.motorInter)();
                }
                layer.msg(result.stateMsg);
            }
        })
    }

    // 监听页面是否被浏览，未浏览则清除定时器
    document.addEventListener('visibilitychange', function () {
        console.log(document.hidden)
        if (document.hidden) {
            // 进入后台不被用户浏览
            clearTimeout(timer);
        } else if (document.hidden == false) {
            // 进入前台,用户正在浏览
            clearTimeout(timer);
            timeFun(getMotors,config.motorInter)();
        }
    });

});